package be.jprojects.subscription.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import be.jprojects.subscription.controllers.ListenersController;
import be.jprojects.subscription.gui.i18n.TranslatableButton;
import be.jprojects.subscription.gui.listeners.CRUDActionListener;

public class CRUDButtonPanel extends JPanel implements ActionListener, CRUDActionListener {
	private TranslatableButton newButton, updateButton, deleteButton, saveButton, cancelButton;
	public CRUDButtonPanel(String name) {
		super.setName(name);
		setLayout(new GridLayout(1, 5));
		newButton = new TranslatableButton("new");
		updateButton = new TranslatableButton("update");
		deleteButton = new TranslatableButton("delete");
		saveButton = new TranslatableButton("save");
		cancelButton = new TranslatableButton("cancel");
		
		newButton.setEnabled(true);
		updateButton.setEnabled(true);
		deleteButton.setEnabled(true);
		saveButton.setEnabled(false);
		cancelButton.setEnabled(false);
		
		add(newButton);
		add(updateButton);
		add(deleteButton);
		add(saveButton);
		add(cancelButton);
		
		newButton.addActionListener(this);
		updateButton.addActionListener(this);
		deleteButton.addActionListener(this);
		saveButton.addActionListener(this);
		cancelButton.addActionListener(this);
		ListenersController.getInstance().addCRUDActionListener(super.getName(), this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		JButton source = (JButton) e.getSource();
		System.out.println(source.getName());
		if (source.getName().equals("new"))
			ListenersController.getInstance().newActionPerformed(super.getName(), e);
		else if (source.getName().equals("update"))
			ListenersController.getInstance().updateActionPerformed(super.getName(), e);
		else if (source.getName().equals("delete"))
			ListenersController.getInstance().deleteActionPerformed(super.getName(),e);
		else if (source.getName().equals("save"))
			ListenersController.getInstance().saveActionPerformed(super.getName(), e);
		else if (source.getName().equals("cancel"))
			ListenersController.getInstance().cancelActionPerformed(super.getName(), e);
	}

	@Override
	public void deleteActionPerformed() {
		editable(false);
	}

	@Override
	public void newActionPerformed() {
		editable(false);
	}


	@Override
	public void updateActionPerformed() {
		editable(false);
	}
	
	@Override
	public void saveActionPerformed() {
		editable(true);
	}

	@Override
	public void cancelActionPerformed() {
		editable(true);
	}

	private void editable(boolean editable) {
		newButton.setEnabled(editable);
		updateButton.setEnabled(editable);
		deleteButton.setEnabled(editable);
		saveButton.setEnabled(!editable);
		cancelButton.setEnabled(!editable);
	}
}